﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using Emgu.CV.Features2D;

namespace ImageHandler
{
	public class FileImagePersistence
	{
		
		private static bool SaveImageFeatures(ImageFeature[] features, String fileName)
		{
			Stream stream = File.Open(fileName, FileMode.Create);
			var binFormatter = new BinaryFormatter();
			binFormatter.Serialize(stream, features);
			stream.Close();
			return true;
		}
		
    public static bool SaveImageFeatures(String fileImage, String fileName)
    {
            ImageMatch imageMatch = new ImageMatch();
            imageMatch.LoadGivenImageFromImageFile(fileImage);
            return SaveImageFeatures(imageMatch.GivenImageFeatures, fileName);
    }

		public static bool LoadImageFeatures(out ImageFeature[] features, String fileName)
		{
			Stream stream = File.Open(fileName, FileMode.Open);
			var binFormatter = new BinaryFormatter();
			features = (ImageFeature[])binFormatter.Deserialize(stream);
			stream.Close();
			return true;
		}
		
		public static bool DeleteFile(String fileName)
		{
			File.Delete(fileName);
			return true;
		}

		public static Byte[] ReadFileBytes(String fileName)
		{
			return File.ReadAllBytes(fileName);
		}

		public static bool GenerateFeaturesForFiles(List<String> fileNames)
		{

			foreach (var fileName in fileNames)
			{
				ImageMatch imageMatch = new ImageMatch();
				imageMatch.LoadGivenImageFromImageFile(fileName);
				SaveImageFeatures(imageMatch.GivenImageFeatures, String.Format("{0}.bin", fileName));
			}

			return true;
		}

	}
}
